import JsSIP from 'jssip'

export const jssipInit = (boolean) => {
    /*
      boolean用于开启关闭jssip自带的打印
    */
    let Session = null;
    let userAgent = null
    let outgoingSession = null; //用于分辨呼出
    let incomingSession = null; //用于分辨呼入
    let localStream = new MediaStream(); //媒体流
    let audioView = new Audio; //audio标签
    let regFs = ''

    JsSIP.C.SESSION_EXPIRES = 120
    JsSIP.C.MIN_SESSION_EXPIRES = 120

    if (boolean) JsSIP.debug.enable('JsSIP:*');
    else JsSIP.debug.disable('JsSIP:*');

    // 分机号注册
    function reg(ext) {
        regFs = ext.regFs //这里是FS注册地址
        /**/
        // 分机号注册 格式 sip: + 分机号码 + @ + FS注册地址
        //let sip_uri_ = 'sip:' + ext.exNumber + '@' + ext.regFs
        let sip_uri_ = 'sip:' + '888' + '@' + '@192.168.2.199'
        // Fs的 ws协议地址
        //let ws_uri_ = 'wss://' + ext.regFs + ':' + ext.port + '/ws'
        let ws_uri_ = 'ws://192.168.2.199:8088'

        let socket = new JsSIP.WebSocketInterface(ws_uri_)

        let configuration = {
            sockets: [socket],
            uri: sip_uri_,
            password: sip_password_,
            display_name: "'" + ext.exNumber + "'",
            contact_uri: 'sip:' + ext.exNumber + '@' + ext.regFs + ';transport=wss',
            //自动注册
            // register: true,
            //是否开启会话计时器,默认是true
            // session_timers: true,
            register_expires: 86400, //多长时间重连一次，这个数字为最大值
            trace_sip: true
        }

        //注册
        userAgent = new JsSIP.UA(configuration)
        userAgent.start()
        userAgent.register()
        /*
         确保每次流程只注册一次，保证下次注册之前注销
         不然会建立多个ws链接，导致服务器找不到正确的接口
         和多次重连与连接不稳定
        */

        //注册成功
        userAgent.on('registered', () => {
            console.log('注册成功')
        })

        //注册即将失效
        userAgent.on('registrationExpiring', () => {
            console.log('注册即将失效')
        })

        //注册失败
        userAgent.on('registrationFailed', () => {
            console.log('注册失败')
        })

        //重新注册
        userAgent.on('registrationExpiring', () => {
            console.log('重新注册')
        })

        //注销回调
        userAgent.on('unregistered', () => {
            console.log('解除注册')
        })



        //呼入与呼出
        userAgent.on('newRTCSession', function (data) {
            Session = data.session
            if (data.originator == "local") {
                //外呼
                outgoingSession = data.session
                outgoingSession.connection.addEventListener('track', (event) => {
                    audioView.srcObject = event.streams[0];
                    audioView.play();
                    audioView.volume = 1;
                });


            } else {
                //呼入
                incomingSession = data.session
                let receivers = incomingSession.connection.getReceivers();
                incomingSession.on('accepted', function (data) {
                    if (receivers) {
                        receivers.forEach(item => {
                            localStream.addTrack(item.track);
                        })
                        audioView.srcObject = localStream;
                        audioView.play();
                        audioView.volume = 1;
                    }

                })


                incomingSession.on("progress", function (data) {
                    console.log('来电振铃')
                })

                incomingSession.on('failed', function (e) {
                    console.log('来电通话失败')
                })

                incomingSession.on('ended', function (e) {
                    console.log('来电挂断')
                });

            }

            // 静音时触发
            Session.on('muted', function (data) {
                console.log('通话静音中')
            })

            //取消静音时触发
            Session.on('unmuted', function (data) {
                console.log('恢复通话')
            })

            //发送DTMF讯号的回调
            Session.on('newDTMF', function (data) {
                let dtmfSession = data.dtmf
                dtmfSession.on('succeeded', function (data) {
                    console.log('发送成功')
                })

                dtmfSession.on('failed', function (data) {
                    console.log('发送失败')
                })


            })


        })

    }

    //注销注册
    function unreg() {
        let options = {
            all: true
        }
        userAgent.unregister(options)
        userAgent = null
    }

    // 拨号
    function testCall(phoneNum) {
        var eventHandlers = {
            //振铃中
            progress: function () {
                console.log('振铃中')
            },
            //呼叫失败
            failed: function () {
                console.log('呼叫失败')
            },
            //通话结束
            ended: function () {
                console.log('通话结束')
            },
            //通话中
            confirmed: function () {
                console.log('通话中')
            }
        }

        var options = {
            'eventHandlers': eventHandlers,
            'extraHeaders': ['X-Foo: foo', 'X-Bar: bar'],
            'mediaConstraints': {
                'audio': true,
                'video': false,
                mandatory: {
                    maxWidth: 640,
                    maxHeight: 360
                },
            },
        };
        userAgent.call('sip:' + phoneNum + '@' + regFs, options)

    }

    // 挂断
    function hangup() {
        userAgent.terminateSessions()
    }


    //静音的方法
    function Mute() {
        let options = {
            audio: true,
            video: true,
        }
        Session.mute(options)
    }

    //取消静音的方法
    function unMute() {
        let options = {
            audio: true,
            video: true
        }
        Session.unmute(options)
    }

    //保持的方法\
    function Hold() {
        let options = {
            useUpdate: false
        }
        let done = function () {
            console.log('保持中')
        }
        Session.hold(options, done)
    }

    //取消保持的方法
    function unHold() {
        let options = {
            useUpdate: false
        }
        let done = function () {
            console.log('取消保持')
        }
        Session.unhold(options, done)
    }

    //输出DTMF信号
    function sendtmf(value) {
        Session.sendDTMF(value)
    }


    //接听
    function answer() {
        let options = {
            'extraHeaders': ['X-Foo: foo', 'X-Bar: bar'],
            'mediaConstraints': {
                'audio': true,
                'video': false,
            },
            // 'mediaStream': localStream,
        }
        Session.answer(options);

    }

    return {
        reg,
        unreg,
        testCall,
        hangup,
        answer,
        Mute,
        unMute,
        Hold,
        unHold,
        sendtmf
    }

}